package com.mall.shop.service.impl;

import com.mall.shop.constants.SecurityConstant;
import com.mall.shop.constants.SmsConstrant;
import com.mall.shop.dto.auth.LoginDto;
import com.mall.shop.dto.auth.RegisterDto;
import com.mall.shop.entity.member.Member;
import com.mall.shop.feign.member.MemeberFeignService;
import com.mall.shop.feign.thirdparty.ThirdPartyFeignService;
import com.mall.shop.service.AuthService;
import com.mall.shop.utils.BeanCopyUtil;
import com.mall.shop.utils.R;
import com.mall.shop.vo.auth.UserInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service("authService")
public class AuthServiceImpl implements AuthService {

    @Autowired
    private MemeberFeignService memeberFeignService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private ThirdPartyFeignService thirdPartyFeignService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserInfoVO loginByMobile(LoginDto loginDto) {
        R<Member> result = memeberFeignService.findMemberByMobile(loginDto.getMobile());
        if (Objects.isNull(result.getData())) {
            throw new RuntimeException("用户不存在");
        }
        return BeanCopyUtil.singleCopy(result.getData(), UserInfoVO.class);
    }

    @Override
    public Boolean register(RegisterDto registerDto) {
        if (Objects.isNull(registerDto)) {
            throw new RuntimeException("请填写注册信息");
        }
        R<Member> result = memeberFeignService.findMemberByMobile(registerDto.getMobile());
        if (Objects.nonNull(result.getData())) {
            throw new RuntimeException("用户已存在");
        }
        String code = Objects.requireNonNull(redisTemplate.opsForValue().get(SmsConstrant.SMS_CODE_CACHE_PREFIX + registerDto.getMobile())).toString();
        if (registerDto.getCode().equals(code)) {
            // 验证码匹配成功之后将验证码从redis中删除
            redisTemplate.delete(SmsConstrant.SMS_CODE_CACHE_PREFIX + registerDto.getMobile());
            String encode = passwordEncoder.encode(registerDto.getPassword());
            Member member = BeanCopyUtil.singleCopy(registerDto, Member.class);
            member.setPassword(encode.substring(SecurityConstant.BCRYPT.length()));
            return memeberFeignService.register(member).getData();
        }
        return false;
    }
}
